package com.yanghui.agent.agentBytebuddy;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.*;
import net.bytebuddy.matcher.ElementMatchers;
import redis.clients.jedis.Jedis;

import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;

public class AgentBootCostTime {

    public static class TimeInterceptor {
        @RuntimeType
        public Object intercept(@This Object obj, @Origin Method method,
                                @AllArguments Object[] allArguments, @SuperCall Callable<?> callable) throws Exception{
            long start = System.currentTimeMillis();
            try {
                return callable.call();
            } finally {
                System.out.println("agent:TimeInterceptor:拦截方法：" + method.getDeclaringClass().getName() + "." + method.getName()
                        + ":" + (System.currentTimeMillis() - start) + "ms");
            }
        }
    }

    public static void premain(String agentArgs, Instrumentation inst) throws Exception {
        System.out.println("=================================agent==============================================");
        AgentBuilder agentBuilder = new AgentBuilder.Default();
        AgentBuilder.Transformer transformer = (builder, typeDescription, classLoader, module) -> {
            builder = builder
                    .method(ElementMatchers.named("test1"))
                    .intercept(MethodDelegation.to(new TimeInterceptor()));
            return builder;
        };
        agentBuilder.type(ElementMatchers.named("com.yanghui.agent.service.AgentServiceMain"))
                .transform(transformer)
                .installOn(inst);
    }
}
